//接口封装 request.js
import axios from 'axios'
// 导入弹框提示组件
import { Message} from 'element-ui'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// import { store } from '@/store/index.js'
// 自定义实例默认值
const service = axios.create({
  //配置请求的根路径[接口地址]
  baseURL: '/zuul',
  // headers:{ accessToken:sessionStorage.getItem("token") },
  // withCredentials: false,
  timeout: 20000
})

// 请求拦截器
//所有的网络请求都会先走这个方法
service.interceptors.request.use(
  config => {
    // if(store.state.token){
    // 	config.headers.Authorization = store.state.token;
    // }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
//所有的网络请求返回数据之后都会先走这个方法
service.interceptors.response.use(
  (response) => {
    const res = response.data
      if(res.code == 401||res.code == 402){
          Message({
              message: res.msg,
              type: 'error',
              duration: 5 * 1000
          })
          return Promise.reject('error')
      }else if (response.status !== 200) {
      Message({
        message: response.msg,
        type: response.code,
        duration: 5 * 1000
      })
      return Promise.reject('error')
    } else {
      return res
    }
  },(error) => {
        let { message } = error;
        if (message == "Network Error") {
            message = "后端接口连接异常";
        }
        else if (message.includes("timeout")) {
            message = "系统接口请求超时";
        }
        else if (message.includes("Request failed with status code")) {
            message = "系统接口" + message.substr(message.length - 3) + "异常";
        }
        Message({
            message: message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
  }
)

export default service
